import serial
import numpy as np
import matplotlib.pyplot as plt
from scipy.fft import fft


# open the serial port at a specific baud rate
ser = serial.Serial('COM10', 200000)
x_values= np.arange(0, 1000, 1)
y_values= np.arange(-2,2.00,0.004)
fig, ax = plt.subplots(figsize=(8, 6))

line, = ax.plot(x_values, y_values)
# read data from the serial port
while True:
    data=ser.read(1000)
    for i in range(0, 1000):
        y_values[i] = ((data[i] * 3.3/ 255)-2)
        # print(y_values)

       
    

    # print(type(y_values))
    # minimum=y_values.min()
    # maximum=y_values.max()
    # count=0
    fft_signal = fft(y_values,4096)
    freqs = np.fft.fftfreq(4096, 1/20000)   ## 4.5 for atmega and 1 for Tiva
    max_index = np.argmax(np.abs(fft_signal))
    freq = freqs[max_index]
    # y_values=np.abs(fft(y_values,1000))
    # x_values=freqs
    
    if(freq>100): 
        scale=freq 
    else:
        scale=100
    
    x1=0
    x2=100000/scale
    y2=y_values.max()+ 0.5
    y1=y_values.min()- 0.5
    ax.set_xlim(x1, x2)
    ax.set_ylim(y1,y2)
    

    #### adjust x scaling 



    # plt.plot(freqs, np.abs(fft_signal))
    # plt.show()
    tx=ax.text(x2*0.68,y2*0.8, 'Frequency = ' + str(round(freq,2)) + ' Hz')
    line.set_ydata(y_values) 
    plt.draw() 
    plt.pause(0.005)
    tx.remove()